package com.briup.auth.config;

import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Configuration
@EnableSwagger2
public class Swagger2Config {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.briup.auth.controller"))
                .paths(PathSelectors.any())
                .build()
                .securitySchemes(security())
                .securityContexts(securityContexts());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("crm客户关系管理系统-登录认证子服务")
                .description("个人制作，http://www.aaa.com")
                .termsOfServiceUrl("http://www.aaa.com")
                .version("1.0")
                .build();
    }
    /**
     * 设置认证中显示的基本信息
     * @return
     */
    private List<ApiKey> security(){
        return Collections.singletonList(new ApiKey("Authorization","token","header"));
    }

    private List<SecurityContext> securityContexts(){
        List<String> antPaths = new ArrayList<>();
        antPaths.add("/test/**");
        return Collections.singletonList(SecurityContext.builder()
                .securityReferences(defaultAuth())
                .forPaths(antPathsCondition(antPaths))
                .build());
    }

    private Predicate<String> antPathsCondition(List<String> antPaths){
        List<Predicate<String>> list = new ArrayList<>();
        antPaths.forEach(path->list.add(PathSelectors.ant(path)));
        return Predicates.or(list);
    }

    private List<SecurityReference> defaultAuth(){
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        return Collections.singletonList( new SecurityReference("Authorization", authorizationScopes));
    }



}